import { Request, Response } from 'express';
import Vote from '../models/Vote';
import { ethers } from 'ethers';
import votingFactoryAbi from '../chain/votingFactoryAbi.json'; 

// 获取我参与的投票（链上查询）
export const getMyJoinedVotes = async (req: Request, res: Response) => {
  try {
    // 前端传入的钱包地址
    const userAddress = req.query.address as string;
    if (!userAddress) return res.status(400).json({ success: false, msg: '缺少钱包地址' });

    // 连接以太坊节点和合约
    const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
    const contract = new ethers.Contract(process.env.VOTING_FACTORY_ADDRESS!, votingFactoryAbi, provider);

    // 1. 查所有已上链的投票（数据库中有chainVoteId的）
    const votes = await Vote.find({ chainVoteId: { $ne: null } });

    // 2. 批量在链上查询用户是否参与过这些投票
    const joinedVotes: any[] = [];
    await Promise.all(votes.map(async (v) => {
      try {
        // 查询用户在该投票的选择
        const choice = await contract.getVoterChoice(userAddress, v.chainVoteId);
        // ethers 6.x: MaxUint256 用 BigInt，判断是否投过票
        if (choice && choice.toString() !== ethers.MaxUint256.toString()) {
          // 检查是否过期
          const expired = v.expireAt < new Date();
          if (expired && !v.expired) {
            await Vote.findByIdAndUpdate(v._id, { expired: true });
          }
          joinedVotes.push({
            ...v.toObject(),
            expired,
            maxVoters: v.maxVoters,
            currentVoters: v.currentVoters
          });
        }
      } catch (e) {
        // 忽略单个投票的链上查询错误
      }
    }));

    // 返回用户参与过的投票列表
    res.json({ success: true, data: joinedVotes });
  } catch (e: any) {
    res.status(500).json({ success: false, msg: '查询失败', error: e.message });
  }
};
